<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Layui - 编辑页面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../bootstrap/bootstrap.css" media="all">
    <script src="../layui/layui.all.js" charset="utf-8"></script>
    <script src="../js/jquery.js"></script>
    <script src="../js/global.js" charset="utf-8"></script>
    <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
    <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
    <style>
        .layui-form-label {
            width: 120px;
        }

        .layui-input {
            width: 95%;
        }

        .editor-toolbar {
            border: 1px solid #ccc;
        }

        .editor-text-area {
            border: 1px solid #ccc;
            border-top: 0;
            height: 400px;
        }
    </style>
</head>

<body>
<form class="layui-form" id="edit-form" action="" style="margin: 20px;">

    <div class="layui-form-item">
        <label class="layui-form-label">一级菜单</label>
        <div class="layui-input-block">
            <select name="parentid" id="parentid" lay-verify="required" required>
                <option value="1">公司介绍</option>
                <option value="2" selected="selected">产品中心</option>
                <option value="3">解决方案</option>
                <option value="4">技术支持</option>
                <option value="5">毕昇杯</option>
                <option value="6">联系我们</option>

            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">类型</label>
        <div class="layui-input-block">
            <select name="menutype" id="menutype" lay-verify="required" lay-filter="menutype" required>
                <option value="1" selected="selected">文章</option>
                <option value="2">设备列表</option>
                <option value="3">公告列表</option>
                <option value="4">资质列表</option>
                <option value="5">作品列表</option>
                <option value="6">文件列表</option>
                <option value="7">页面</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" id="name" lay-verify="name" lay-reqtext="名称不能为空" placeholder="请输入" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">序号</label>
        <div class="layui-input-block">
            <input type="number" name="seq" id="seq" lay-verify="seq" lay-reqtext="序号不能为空" value="1" placeholder="请输入名称" class="layui-input">
        </div>
    </div>
    <div id="htmlvaldiv">
        <label class="layui-form-label">文章内容</label>
        <div>
            <div id="editor-toolbar" class="editor-toolbar"></div>
            <div id="editor-text-area" class="editor-text-area"></div>
        </div>
        <textarea id="htmlval" name="htmlval" style="display: none;"></textarea>
    </div>
    <div style="text-align: center;">
        <input type="hidden" id="id" name="id" value="" />
        <button type="submit" class="layui-btn" lay-submit="" lay-filter="formDemo">保存修改</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="closePage()">取消编辑</button>
    </div>

</form>

<script>
    //Demo
    var id = getQueryString("id");

    var form;
    var submiting = false;
    layui.use(['layer', 'form'], function () {
        var layedit = layui.layedit;

        form = layui.form;
        initedit();
        initData(form);
        if (id != null && id.length > 0) {

            $.ajax({
                type: "POST", // 修改回 POST 方法
                url: '/techshine_war/menu/byid', // 移除 URL 中的 ?id=... 部分，因为 POST 方法通常将数据放在请求体中
                async: false,
                data: { // 添加 data 属性，用于存放请求体数据
                    "id": id // 将 id 封装到请求体中
                },
                success: function (res) {
                    echoEdit(res.result);
                    $("#seq").val(res.result.seq);
                    $("#name").val(res.result.name);
                    $("#parentid").val(res.result.parentid);
                    $("#menutype").val(res.result.menutype);
                    $("#htmlval").val(res.result.htmlval);
                    if (res.result.menutype == '2') {
                        $("#htmlvaldiv").hide()
                    }
                    if (res.result.htmlval != null) {
                        editor.setHtml(res.result.htmlval)
                    }
                    form.render('select');
                }
            });
        } else {
            form.render('select');
        }
        // 自定义验证规则
        form.verify({
            name: function (value) {
                if (value.length < 1 || value.length > 20) {
                    return '名称长度1-20';
                }

            },
            seq: function (value) {
                if (value.length < 1) {
                    return '请输入序号';
                }

            },

        });
        // 监听提交
        form.on('submit(formDemo)', function (data) {
            if (submiting) {
                return false;
            }

            $("#htmlval").val(editor.getHtml());
            var data = $("form").serializeArray();
            console.info(JSON.stringify(data.field))
            $.ajax({
                type: "post", // 修改为PUT请求以实现更新操作
                url: '/techshine_war/menu/update', // 更新接口地址
                async: false,
                data: data,
                success: function (res) {
                    if (res.result.status === 200) { // 更改为 res.result.status
                        submiting = true;
                        layer.msg(res.data.msg); // 注意：此处应使用 res.result.msg 而非 res.data.msg，因为后端返回的数据结构中msg位于result对象内
                        parent.reload();
                        closePage();
                    }
                }
            });
            return false;
        });
        form.on('select(menutype)', function (data) {
            var sval = data.value;
            if (sval == '1') {
                $("#htmlvaldiv").show()
            } else {
                $("#htmlvaldiv").hide()
            }
            form.render(); // 更新全部
            form.render('select');
        });
    });

    function initData(form) {

    }
    var editor;
    function initedit() {
        const E = window.wangEditor;
        // Change language
        const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
        E.i18nChangeLanguage(LANG)

        const editorConfig = {
            MENU_CONF: {}
        }
        editorConfig.MENU_CONF['uploadImage'] = {
            server: '/techshine_war/menu/uploadpic?imgtype=3',
            timeout: 5 * 1000, // 5s

            fieldName: 'custom-fileName',
            meta: { token: 'xxx', a: 100 },
            metaWithUrl: true, // join params to url
            headers: { Accept: 'application/json' },
            maxFileSize: 10 * 1024 * 1024, // 10M

            base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

            onBeforeUpload(file) {
                //console.log('onBeforeUpload', file)

                return file // will upload this file
                // return false // prevent upload
            },
            onProgress(progress) {
                //console.log('onProgress', progress)
            },
            onSuccess(file, res) {
                //console.info(1)
                //return res.data[0]
                //console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
                //alert(res.message)
                console.log('onFailed', file, res)
            },
            onError(file, err, res) {
                //alert(err.message)
                console.error('onError', file, err, res)
            },
            customInsert(res, insertFn) {
                console.info(res)
    //  console.log('customInsert', res)          // const imgInfo = res.data[0];
                // const { url, alt, href } = imgInfo
                // if (!url) throw new Error(`Image url is empty`)

                // console.log('Your image url ', url)
                insertFn(res.data[0])
            }
        }

        editor = E.createEditor({
            selector: '#editor-text-area',
            html: '请输入文章',
            config: editorConfig,
            onChange(editor) {
                console.log(editor.getHtml())
                // 选中文字
                const selectionText = editor.getSelectionText()
                document.getElementById('selected-length').innerHTML = selectionText.length
                // 全部文字
                const text = editor.getText().replace(/\n|\r/mg, '');
                console.info(text)
            }
        })
        const toolbar = E.createToolbar({
            editor,
            selector: '#editor-toolbar',
            // config: {}
        })
    }
</script>